package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //创建一个antpathmatcher对象
    protected AntPathMatcher antPathMatcher=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;

//        定义该放行的资源//注意这个地方一定要写/表示绝对路劲
        String[] uris={"/employee/login",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"};

//        获取当前的访问资源
        String requestURL = request.getRequestURI();
        //判断是否为放行的路径
        Boolean flag=checkUrls(uris,requestURL);
        if(flag){
            //如果为true，放行
            filterChain.doFilter(request, response);
            return;
        }
        //判断登录状态，登入成功直接放行
        if(request.getSession().getAttribute("user")!=null){
            log.info("用户已经登入用户的id为:"+request.getSession().getAttribute("user"));
            filterChain.doFilter(request, response);
            return;
        }

        Object employee = request.getSession().getAttribute("employee");
        if(employee!=null){
            filterChain.doFilter(request, response);
            return;
        }
        String jsons = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(jsons);

    }

    private Boolean checkUrls(String[] urls, String requestURL) {
        for (String url : urls) {
            if(antPathMatcher.match(url, requestURL)){
                return true;
            }
        }
        return false;
    }
}
